<?php
include 'int.php';
?>
<html>
<head>
<style>
.errmsg{
	color:red;
}
</style>
</head>
<body>
<?php
if (isset($_COOKIE["login_session"]) && $_COOKIE["login_session"]!=""){
	header('Location: waitroom.php');
}else if (isset($_POST["name"])){
	if (!$mysqlpdo) {
		printf("Connect failed: %s\n", mysqli_connect_error());
		exit();
	}
	
	if ($stmt = $mysqlpdo->prepare("SELECT g.u_num FROM join_game g WHERE g.u_num=(SELECT MIN(u_num) FROM join_game g2 WHERE g2.joined=0)")) {
		$stmt->execute();
		if ($result = $stmt->fetch(PDO::FETCH_BOTH)){
			if ($stmt2 = $mysqlpdo->prepare("SELECT g.u_num FROM join_game g WHERE g.joined>0 AND g.user=?")) {
				$stmt2->bindParam(1, $_POST["name"], PDO::PARAM_STR);
				$stmt2->execute();
				if ($stmt2->fetch(PDO::FETCH_BOTH)){
					echo "<div style=\"errmsg\">User name already exist</div>";
					header('Refresh: 2; url=index.php');
					exit();
				}
			}else{
				print("<div style=\"errmsg\">Error in SQL1</div>");
			}
				
			printf("Your id is %d\n", $result);
			$session = hash("md5", time()+$_POST["name"]);
			printf("Session: %s", $session);
			if ($stmt3 = $mysqlpdo->prepare("UPDATE join_game g SET g.joined=1, g.timeout=NOW(), g.user=?, g.session=?, g.photo=1 WHERE g.u_num=?")){
				$stmt3->bindParam(1, $_POST["name"], PDO::PARAM_STR);
				$stmt3->bindParam(2, $session, PDO::PARAM_STR);
				$stmt3->bindParam(3, $result[0], PDO::PARAM_INT);
				$stmt3->execute();
				setcookie("login_session", $session, time()+3600*3);
				header('Location: waitroom.php?uid='.$result[0]);
			}else{
				print("<div style=\"errmsg\">Error in SQL2</div>");
			}
		}else{
			printf("Full.");
			header('Refresh: 2; url=index.php');
			exit();
		}
	}
}
?>
Please input a username<br />
<form method="post">
<input type ="text" name="name" maxlength="30" /><br />
<input type ="Submit" value="submit" />
</form>
</body>
</html>